
var inventory;
var memberPrice;
var shopId = GetQueryString('shopId');
var specification;
var lnt;
var shopPhone;
var shopAddress;
var shopName;
var goodsId = GetQueryString('goodsId');
var ifClickCart = 'false';
var ifClickBuy = 'false';
var userId = GetQueryString('userId');
var goodsName = '';
var chooseCount = '';
var topHeight1 =0;
var topHeight2 =0;
var topHeight3 =0;
$(function () {
    if(userId==undefined||userId==null||userId==""){
        userId = "";
    }else{
        setItem('userId',userId);
    }
})
//初始化数据
$(function () {
	$.ajax({
		url:'/goodsC/receptionDetails',
		dataType:'json',
		data:{
			id:GetQueryString('goodsId'),
		},
		type:'post',
		success:function (data) {
			initBanner(data.datas.mainImage);
			initData(data.datas);
            if(data.datas.customersdatas.length>0){
                initComment(data.datas);
            }else{
                $('.comment-big-box').css('pointer-events','none');
                $('.comment-big-box').html('<div class="title-box">\n' +
                    '<span class="comment-number">用户评价 (0)<i></i></span></div>');
            }
        }
	})
	var speWidth = $('.specification_img').width()/100;
	var BodyWidth = $('body').width()*speWidth;
	$('.specification_img').css('height',''+BodyWidth+'px');
})

//轮播图
function initBanner(a) {
	var bannerImg = a.split(',');
	for(var i=0;i<bannerImg.length;i++){
		$('<div class="swiper-slide">\n' +
            '<a href="#">\n' +
            '<img src="'+bannerImg[i]+'">\n' +
            '</a>\n' +
            '</div>').appendTo($('#banner'));
	}
	$('#spe_img').attr('src',bannerImg[0]);
    //轮播图
    var swiper = new Swiper('.swiper-container4', {
        loop: true,
        autoplay: 5000,
        pagination: '.swiper-pagination4',
        paginationClickable: true,
        paginationType: 'fraction'
    });

}

//轮播图(静态，正式数据后删掉)
// var swiper = new Swiper('.swiper-container4', {
//     loop: true,
//     autoplay: 5000,
//     pagination: '.swiper-pagination4',
//     paginationClickable: true,
//     paginationType: 'fraction'
// });

//商品数据
function initData(b) {
    lnt = b.address;
    shopPhone = b.phone;
    shopName = b.shopName;
    shopAddress = b.shopAddress;
    goodsName = b.goodsName;
	if(b.payOnDelivery==1){
        $('.goods-title-box').html('<span>货到付款</span>'+b.summary);
        $('.cash').show();
        $('.goods-tips').html('<span class="cash">支持货到付款</span>'+b.deliveryArea+'，'+b.deliveryTime+'之前下单，当天送达')
        $('.goods-tips').show();
	}else if(b.payOnDelivery==0){
        $('.goods-title-box').html(b.summary);
        $('.cash').hide();
	}
	$('#marketprice').html('<span>市场价'+b.marketPrice+'</span>');
    $('#memberprice').html('¥'+b.memberPrice);
    $('.price').html('¥'+b.memberPrice);
    $('.inventory').html('库存'+b.inventory+'件');
    $('.code').html('商品编号'+b.goodsCode);
    memberPrice = b.memberPrice;
    inventory = b.inventory;
    specification = b.specification;
    doSpe();

    $('#integrel').html('可抢红包'+b.integral);
    $('.address').html(b.shopAddress);
    $('#phone').attr('href','tel:'+b.phone);
	$('<h4>红包领取形式</h4>').appendTo($('.rule-box'));
    for(var a=0,remark=b.remark.length;a<remark;a++){
    	$('<p><i></i>'+b.remark[a]+'</p>').appendTo($('.rule-box'));
	}
    $('<h4>使用说明</h4>').appendTo($('.rule-box'));
    for(var j=0,remark2=b.remark2.length;j<remark;j++){
        $('<p><i></i>'+b.remark2[j]+'</p>').appendTo($('.rule-box'));
    }
    $(b.details).appendTo($('.goods_detail_box'))
    topHeight2 = $('.comment-big-box').offset().top;
    console.log($('.comment-big-box').offset().top)
}

//评价数据
function initComment(c){
    showStar3(c.shopGraded);
    $('#shopScore').html(c.shopGraded);
    $('.comment-number i').html('('+c.userCustomersSum+')')
    for(var k=0;k< c.commentsSumdatas.length;k++){
        var borderStyle = '';
        if(c.commentsSumdatas[k].commentsType=="差评"){
            borderStyle = 'border:1px solid #c5c5c5;color:#c5c5c5'
        }else{
            borderStyle = '';
        }
        $('<div value="'+ c.commentsSumdatas[k].commentsTypeValue+'" style="'+borderStyle+'">'+ c.commentsSumdatas[k].commentsType+'('+c.commentsSumdatas[k].commentsSum+')</div>').appendTo($('.keyword-box'))
    }

    for(var j=0;j< c.customersdatas.length;j++){
        var imgItem;
        var dataAutor = c.customersdatas[j].customerAvotorr;
        var autor;
        if(dataAutor==""){
            autor = '../img/comment_h.jpg';
        }else{
            autor = dataAutor;
        }

        $('<div class="comment">'+
            '<div class="comment-user">'+
            '<div class="user-img"><img src="'+autor+'" alt="头像"></div>'+
            '<div class="user-info">'+
            '<span class="user-name">'+ c.customersdatas[j].customerPhone+'</span>'+
            '<span class="user-time">'+ c.customersdatas[j].createTime+'</span></div>'+
            //'<div class="user-star star_arr" id="user-star" data-score="'+c.customersdatas[j].gradedValue+'">'+
            //'<span id="add_star2" class="add-star2"></span>'+
            //'<span id="del_star2" class="del-star2"></span>' +
            //'</div>'+
            '</div><div class="comment-detail">'+ c.customersdatas[j].content+'</div>'+
            '</div>').insertBefore($('.view-all-comment'));
        //showStar2(c.customersdatas[j].gradedValue);
    }
    //单个评价分
    //showStar2('.star_arr',ac)
    function showStar2(obj,n){
        var ac = obj.attr('data-score');
        var readStar = obj.offsetWidth;
        var huiStar = $('.del_star2');
        var del_move2=(n*readStar)/5;

        $('.del_star2').css({'background-position':'-'+del_move2+'px 0px','left':''+del_move2+'px'})
        //huiStar.style.backgroundPosition=-del_move2+"px 0px";
        //huiStar.style.left=del_move2+"px";

    }
    topHeight3 = $('.goods_detail_box').offset().top;
    console.log(topHeight3);
}

//用户总评分
function showStar3(n){
    var con_wid3=document.getElementById("comment-star").offsetWidth;
    var del_star3=document.getElementById("del_star3");

    //透明星星移动的像素
    var del_move3=(n*con_wid3)/5;

    del_star3.style.backgroundPosition=-del_move3+"px 0px";
    del_star3.style.left=del_move3+"px";
}

//评价页
$('.view-all-comment,.comment-big-box').click(function () {
    window.location.href="comment_v2.html?shopId="+shopId+"&goodsId="+goodsId;
})

//请选择规格
$('.choose-sku').click(function () {
    var token = getItem('token');
    if(token==null||token==undefined||token==""){
        window.location.href="login.html";
    }else{
        $('#goodsBox').hide();
        $('.specification_box').show();
    }
    ifClickCart = 'false';
    ifClickBuy = 'false';
})

var speB_Id;
var propertiesId;
var param;
var propertiesName;

//获取规格
function doSpe() {
    //无规格商品
    if(!specification){
        $('<div class="detail_count_title">' +
            '<span>数量</span>' +
            '<span class="choose_count">' +
            '<span class="decreace">-</span' +
            '><input type="text"  class="count" style="width: 60px;" value="1"' +
            '><span class="add">+</span>' +
            '</span>' +
            '</div>').appendTo($('.detail_box'));
    }else{
        //规格商品
        $.ajax({
            url:'/specificationC/getSpecification.json',
            dataType:'json',
            data:{
                goodid:GetQueryString('goodsId'),
            },
            type:'post',
            success:function (data) {
                var speData = data.datas;
                for(var i=0;i<speData.length;i++){
                    $('<div class="detail_small_box" id="detail_spe'+speData[i].id+'"></div>').appendTo($('.detail_box'));
                    $('<div class="detail_title">'+speData[i].name+'</div>').appendTo($('#detail_spe'+speData[i].id+''));
                    $('<div class="detail_spe mui-clearfix" id="detailOne_spe'+speData[i].id+'"></div>').appendTo($('#detail_spe'+speData[i].id+''));
                    for(var b=0;b<speData[i].data.length;b++){
                        $('<div class="spe-one" parent="'+speData[i].id+'" son="'+speData[i].data[b].id+'" id="'+speData[i].data[b].id+'">'+speData[i].data[b].content+'</div>').appendTo($('#detailOne_spe'+speData[i].id+''));
                    }
                }
                $('<div class="detail_count_title">' +
                    '<span>数量</span>' +
                    '<span class="choose_count">' +
                    '<span class="decreace">-</span' +
                    '><input type="text" class="count"  value="1"' +
                    '><span class="add">+</span>' +
                    '</span>' +
                    '</div>').appendTo($('.detail_box'));

                //选择加入购物车

                $('.spe-one').click(function () {
                    $(this).addClass('spe_act');
                    $(this).attr('ifAct','true');
                    $(this).siblings().attr('ifAct','false');
                    $(this).siblings().removeClass('spe_act');
                    speB_Id = $(this).attr('parent');
                    var o = $("div[ifAct='true']");
                    param = '';
                    for (var i = 0; i < o.length; i++) {
                        param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                        if (i != o.length - 1) {
                            param += ','
                        }
                    }

                    $.ajax({
                        url:'/goodSpecificationC/getGoodSpecification.json',
                        dataType:'json',
                        data:{
                            goodid:GetQueryString('goodsId'),
                            propertiesid:param,
                        },
                        type:'post',
                        success:function (data) {
                            //获取规格库存，图片
                            if(data.code==1){
                                $('#spe_img').attr('src',data.datas.image);
                                $('.price').html('¥'+data.datas.memberPrice);
                                $('.inventory').html('库存'+data.datas.inventory+'件');
                                inventory = data.datas.inventory;
                                propertiesId = data.datas.id;
                                propertiesName = data.datas.propertiesName;
                                $('#marketprice').html('<span>市场价'+data.datas.maketPirce+'</span>');
                                $('#memberprice').html('¥'+data.datas.memberPrice);
                                $('#integrel').html('可抢红包'+data.datas.integral);
                            }
                        }
                    })
                })
            }
        })
    }
}


$(document).ready(function () {
    //添加
    var count = 1;
    $(document).on('click','.add',function(){
        count++;
        if(count>inventory){
            mui.toast('加入购物车数量不能超过总库存');
            count=inventory;
        }
        if(count>1){
            $('.decrease').css('color','#49c9bb');
        }
        $('.count').val(count);
    })
    //减少
    $(document).on('click','.decreace',function(){
        count--;
        if(count<1){
            count=1;
            $('.decreace').css('color','#bfbcc0');
        }
        if(count>1){
            $('.decreace').css('color','#49c9bb');
        }
        $('.count').val(count);
    })
   //输入产品数量
    $("body").on('change','.count',function(){
        //判断输入数量是否为空或小于1
        if($('.count').val()==''||$('.count').val()==NaN||$('.count').val()<1||$('.count').val()==null||$('.count').val()==undefined){
            $('.count').val(1);
        }
        if($('.count').val()>inventory){
            mui.toast('加入购物车数量不能超过总库存');
            $('.count').val(inventory);
        }
        count = parseInt($('.count').val());
        if(count>1){
            $('.decrease').css('color','#49c9bb');
        }
    })
})

//关闭
$('.colse_spe').click(function () {
    $('.specification_box').hide();
    $('#goodsBox').show();
})

//确定
$('.spe_certain').click(function () {
    if(ifClickCart=='true'){
        addCart();
        return;
    }
    if(ifClickBuy=='true'){
        buy();
        return;
    }
    $('.specification_box').show();
    $('#goodsBox').hide();
   //获取已选择字符串拼接
    var speStr = '';
    $('.spe_act').each(function () {
        speStr+=$(this).html()+', ';
    })
    speStr+='* '+$('.count').val();
    $('.specification_box').hide();
    $('#goodsBox').show();
    $('#top1').hide();
    $('#top2').show();
    $('.swiper-container4').css('padding-top','44px');
    $('.choose-sku').html('<span class="choose">已选择</span><span class="choose-yet">'+speStr+'</span>')
})

//点击加入购物车
$('.add-cart').click(function () {
    ifClickCart = 'true';
    ifClickBuy = 'false';
    getSpe();
})

function getSpe() {
    if(propertiesId==undefined||propertiesId==null||propertiesId==""){
        $('.specification_box').show();
        $('#goodsBox').hide();
        $('#top2').hide();
        $('#top1').show();
        $('.swiper-container4').css('padding-top','0');
    }else{
        if(ifClickCart=='true'){
            addCart();
            return;
        }
        if(ifClickBuy=='true'){
            buy();
            return;
        }
    }
}


//加入购物车
function addCart() {
    $.ajax({
        url:'/ShoppingCartC/addUserShoppingCart.json',
        dataType:'json',
        data:{
            shopId:GetQueryString('shopId'),
            goodsId:GetQueryString('goodsId'),
            count:$('.count').val(),
            specificationId:propertiesId,
            token:getItem('token'),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                //获取已选择字符串拼接，待测试
                var speStr = '';
                $('.spe_act').each(function () {
                    speStr+=$(this).html()+', ';
                })
                speStr+='* '+$('.count').val();
                $('.specification_box').hide();
                $('#goodsBox').show();
                mui.toast('加入购物车成功');
                propertiesId = '';
                $('.spe-one').removeClass('spe_act');
                $('.spe-one').attr('ifact','false');
                $('#top1').hide();
                $('#top2').show();
                $('.swiper-container4').css('padding-top','44px');
                $('.choose-sku').html('<span class="choose">已选择</span><span class="choose-yet">'+speStr+'</span>')
            }
            if(data.code==0){
                mui.toast(data.msg);
                propertiesId = '';
                return;
            }
            if(data.code==-1){
                window.location.href="login.html";
            }
        }
    })
}

//店铺导航
$('.address').click(function(){
    var url = encodeURI("map.html?shopName="+shopName+"&shopAddress="+shopAddress+"&shopPhone="+shopPhone+"&lnt="+lnt);
    window.open(url,"_self");
})


//滚动高度
$(window).scroll(function() {
    var toTopHeight = (document.documentElement.scrollTop || 0) + (document.body.scrollTop || 0);
    //console.log(document.documentElement.scrollTop || 0 + document.body.scrollTop || 0);
    if(toTopHeight>10&&toTopHeight<topHeight2){
        //console.log('1')
        $('#top1').hide();
        $('#top2').show();
        $('.swiper-container4').css('padding-top','44px');
        $('#top2').find('li').removeClass('act');
        $('#top2').find('li').children().hide();
        $('#top2').find('li:nth-child(1)').addClass('act');
        $('#top2').find('li:nth-child(1)').append('<span></span>');
    }
    if(toTopHeight>topHeight2&&toTopHeight<topHeight3){
        $('#top2').find('li').removeClass('act');
        $('#top2').find('li').children().hide();
        $('#top2').find('li:nth-child(2)').addClass('act');
        $('#top2').find('li:nth-child(2)').append('<span></span>');
    }
    if(toTopHeight>topHeight3){
        $('#top2').find('li').removeClass('act');
        $('#top2').find('li').children().hide();
        $('#top2').find('li:nth-child(3)').addClass('act');
        $('#top2').find('li:nth-child(3)').append('<span></span>');
    }
    if(toTopHeight>0&&toTopHeight<10){
        $('#top2').hide();
        $('#top1').show();
        $('.swiper-container4').css('padding-top','0');
    }
});

//
$('#goods').click(function () {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    $(this).addClass('act');
    $(this).append('<span></span>');
    $(this).siblings().removeClass('act');
    $(this).siblings().find('span').hide();
})

$('#comment').click(function () {
    document.body.scrollTop = document.documentElement.scrollTop = topHeight2;
    $(this).addClass('act');
    $(this).append('<span></span>');
    $(this).siblings().removeClass('act');
    $(this).siblings().find('span').hide();
})

$('#detail').click(function () {
    document.body.scrollTop = document.documentElement.scrollTop = topHeight3;
    $(this).addClass('act');
    $(this).append('<span></span>');
    $(this).siblings().removeClass('act');
    $(this).siblings().find('span').hide();
})

//跳转购物车
$('.cart').click(function () {
    window.location.href="cart.html";
})

//立即购买
$('.buy').click(function () {
    ifClickBuy = 'true';
    ifClickCart = 'false';
    getSpe();
})

function buy() {
    $.ajax({
        url:'/zuoDanC/confirmOrder.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            goodsId:goodsId,
            goodsSpecificationId:propertiesId,
            num:$('.count').val(),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                var goodsImg = $('#spe_img').attr('src');
                var goodsNum = $('.count').val();
                var speId = propertiesId;
                var totalMoney = data.datas.totalMoney;
                var memberPrice = $('#memberprice').html();
                var propertiesName = propertiesName==undefined?'':propertiesName;
                setItem('goodsImg',goodsImg);
                setItem('goodsNum',goodsNum);
                setItem('speId',speId);
                setItem('totalMoney',totalMoney);
                setItem('memberPrice',memberPrice);
                setItem('propertiesName',propertiesName);
                window.location.href=encodeURI(encodeURI("confirmOrder.html?goodsId="+goodsId+"&goodsNum="+goodsNum+"&speId="+speId+"&goodsImg="+goodsImg+"&goodsName="+goodsName+"&speName="+propertiesName+"&shopName="+shopName+"&totalMoney="+totalMoney+"&memberPrice="+memberPrice));
            }
            if(data.code==0){
                mui.toast(data.msg);
                propertiesId = '';
                return;
            }
            if(data.code==-1){
                window.location.href="login.html";
            }
        }
    })
}

//分享
var ticket;
var timer;
var wxSha1;
$(function () {
    $.ajax({
        url:'/shareC/getAccessToken.json',
        dataType:'json',
        type:'post',
        success:function (data) {
            ticket = data.datas;
            timer = Date.parse(new Date());
            timer = timer / 1000;
            var WXsignature = 'jsapi_ticket=' + ticket + '&noncestr=Wm3WZYTPz0wzccnW&timestamp=' + timer + '&url=' + location.href.split('#')[0]
            wxSha1 = hex_sha1(WXsignature);

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: 'wxfe59dbeae5082ce6', // 必填，公众号的唯一标识
                timestamp: timer, // 必填，生成签名的时间戳
                nonceStr: 'Wm3WZYTPz0wzccnW', // 必填，生成签名的随机串
                signature: wxSha1,// 必填，签名，见附录1
                jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });

            wx.ready(function(){
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，
                wx.checkJsApi({
                    jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function(res) {
                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    },
                    fail:function () {
                        mui.alert('您的微信版本过低，暂不支持分享，请升级微信')
                    }
                });

                //分享给朋友
                wx.onMenuShareAppMessage({
                    title: '分享一个产品，代购整座城市', // 分享标题
                    desc: '同城优选，助利商城', // 分享描述
                    link: 'http://www.ddmzl.com/m/html/goods_v2.html?goodsId='+goodsId+'&shopId='+shopId+'&userId='+userId, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://www.ddmzl.com/m/img/share_logo.jpg', // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                        mui.toast('分享成功');
                        window.location.href='http://www.ddmzl.com/m/html/goods_v2.html?goodsId='+goodsId+'&shopId='+shopId+'&userId='+userId;
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });

                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title: '分享一个产品，代购整座城市', // 分享标题
                    desc: '同城优选，助利商城', // 分享描述
                    link: 'http://www.ddmzl.com/m/html/goods_v2.html?goodsId='+goodsId+'&shopId='+shopId+'&userId='+userId, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://www.ddmzl.com/m/img/share_logo.jpg', // 分享图标
                    success: function () {
                        mui.toast('分享成功');
                        $.ajax({
                            url:'/user/UpdateUserIntegral.json',
                            dataType:'json',
                            data:{
                                token:getItem('token'),
                            },
                            success:function(data){
                                mui.toast('分享成功');
                                window.location.href='http://www.ddmzl.com/m/html/goods_v2.html?goodsId='+goodsId+'&shopId='+shopId+'&userId='+userId;
                            }
                        })
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });
            });
        }
    })
})

$('#share2,#share,.more').click(function () {
    //分享到朋友圈
    if (is_weixn()) {
        mui.alert('请点击右上角分享')
    }else{
        mui.alert('请在微信中打开')
    }
})

var uip = document.getElementById("topPopover");
uip.style.position = "absolute";
$(".mui-backdrop").click(function() {
    $("#topPopover").hide();
    $(".mui-backdrop").hide();
});
$(".mui-table-view-cell").click(function() {
    $("#topPopover").hide();
    $(".mui-backdrop").hide();
});

